package com.jd.cmdb.tsc.jmq;

import com.jd.cmdb.tsc.entity.Task;
import com.jd.jmq.client.producer.Producer;
import com.jd.jmq.common.exception.JMQException;
import com.jd.jmq.common.message.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Created by tianzhengguo on 2016/1/11.
 */
@Service("jmqService")
public class JMQServiceImpl implements JMQService/*<Task>*/ {

    private static final Logger logger = LoggerFactory.getLogger(JMQServiceImpl.class);

    @Resource
    private Producer producer;
    @Value("${jmq.producer.topic}")
    private String topic;

    public void send(Task task) throws JMQException {
        String bizId = UUID.randomUUID().toString();
        logger.info("待发送的消息文本:{},业务ID:{}",buildText(task),bizId);
        Message message = new Message(topic,buildText(task), bizId);
        producer.send(message);
        logger.info("发送完成.");
    }

    public void batchSend(List<Task> tasks) throws JMQException {
        List<Message> messages = new ArrayList<Message>();
        for (Task task : tasks) {
            Message message = new Message(topic, buildText(task), UUID.randomUUID().toString());
            messages.add(message);
        }
        producer.send(messages);
    }


    private String buildText(Task task){
        StringBuilder builder = new StringBuilder();
        builder.append("{\"taskName\":\"").append(task.getName()).append("\",");
        builder.append("\"taskSubName\":\"").append(task.getSubName()).append("\",");
        builder.append("\"id\":\"").append(task.getId()).append("\"}");
        return builder.toString();
    }
}
